<template>
  <view class="message" v-if="message">{{message}}</view>
  <view class="wrap" v-else>
    <view class="cell">
      <view class="label">送货上门</view>
      <switch :checked="delivery" @change="deliveryChange" disabled/>
    </view>
    <view class="cell" v-if="delivery">
      <view class="label" v-if="order.address.realName">
        <view class="location-detail bold ellipsis">{{order.address.province}}{{order.address.city}}{{order.address.district}}{{order.address.address}}</view>
        <view class="phone">{{order.address.realName}}（先生） {{order.address.phone}}</view>
      </view>
      <view class="label" v-else>
        <text>请选择地址</text>
      </view>
      <text class="iconfont icon-xiangyou"></text>
    </view>
    <view class="cell" v-show="false">
      <view class="label bold">立即送出</view>
      <view class="value time">约14:47送达</view>
      <text class="iconfont icon-xiangyou"></text>
    </view>
    <view class="item">
      <view class="title">
        <view class="name">
          <image :src="order.logo" mode="aspectFill" />{{order.shopName}}</view>
        <text class="status">{{['待支付', '待提货', '待归还', '已完成'][item.status - 1]}}</text>
      </view>
      <view class="main" v-for="(goods, index) in order.goodsArr">
        <image :src="goods.pic" mode="aspectFill"></image>
        <view class="info">
          <view class="name ellipsis-2">{{goods.goodsName}}</view>
          <view class="price">¥{{goods._price}}<text>¥{{goods._deposit}}押金</text></view>
        </view>
      </view>
      <view class="btn-group" v-if="order.status === 1">
        <button @click="deleteItem(order.orderNumber)">删除</button>
        <button @click="pay">支付</button>
        <view class="total">
          <view class="total-price">总计: <text>¥{{order._total}}</text></view>
          <view class="count">共{{order.goodsArr.length}}件商品</view>
        </view>
      </view>
    </view>
    <uni-card is-full custom-class="mt">
      <view class="order-info">订单编号: {{order.orderNumber}}</view>
      <view class="order-info">下单时间: {{order.createTime}}</view>
      <view class="order-info">支付方式: 微信支付</view>
      <view class="order-info">支付时间: 2019-09-07 23:43:06</view>
      <view class="order-info">配送方式: {{delivery ? '普通配送' : '无需配送'}}</view>
    </uni-card>
    <uni-card isFull>
      <view class="amount-info"><text>商品总额</text>¥{{order.totalPrice}}</view>
      <view class="amount-info"><text>运费</text>¥8.00</view>
      <view class="amount-info"><text>押金</text>¥{{order.totalDeposit}}</view>
    </uni-card>
  </view>
</template>

<script>
  import uniCard from "@/components/uni-card/uni-card"
  import {Order, User} from '@/apis'
  import {utils, numeral} from '@/utils'
  
  export default {
    data() {
      return {
        message: '',
        isLoading: false,
        delivery: false,
        options: {},
        order: {
          goods: [],
          address: {}
        }
      };
    },
    components: {uniCard},
    methods: {
      getOrderDetail () {
        if (this.isLoading) return
        this.isLoading = true
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        Order.getOrderDetail({
          data: {
            form: {},
            pagination: {},
            query: {
              orderNumber: this.options.number
            }
          }
        }).then(res => {
          console.log('获取订单详情成功')
          console.log(res.data);
          if (res.data.code !== 200) {
            this.message = res.data.message
            uni.showToast({
              title: res.data.message || '订单异常',
              icon: 'none'
            })
            return
          }
          let order = res.data.body
          let total = 0, totalDeposit = 0, totalPrice = 0
          order.goodsArr.map(item => {
            totalPrice += item.price
            totalDeposit += item.deposit
            // 计算价格、押金
            item._price = numeral(item.price).divide(100).format('0.00')
            item._deposit =  numeral(item.deposit).divide(100).format('0.00')
          })
          
          order.total = numeral(totalPrice).add(totalDeposit).format('0.00')
          order._total = numeral(totalPrice).add(totalDeposit).divide(100).format('0.00')
          order.totalPrice = numeral(totalPrice).divide(100).format('0.00')
          order.totalDeposit = numeral(totalDeposit).divide(100).format('0.00')
          this.delivery = order.id
          this.order = order
          
        }, err => console.error(err)).finally(() => {
          this.isLoading = false
          uni.hideLoading()
        })
      },
      toSelectAddress () {
        uni.navigateTo({
          url: '/pages/myAddress/myAddress?type=select'
        })
      },
      deleteItem (orderNumber) {
        if (this.isLoading) return
        this.isLoading = true
        utils.wxAlert('您确定删除此订单？').then(result => {
          Order.deleteOrder({data: {
            form: {},
            query: {
              orderNumber: orderNumber
            },
            pagination: {}
          }}).then(res => {
            if (res.data.code !== 200) {
              utils.wxToastFail(res.data.message)
              return
            }
            utils.wxToastSuccess().then(() => {
              utils.routerBack()
            })
          }).catch(err => console.error(err)).finally(() => {
            this.isLoading = false
            uni.hideLoading()
          })
        })
      },
      deliveryChange (e) {
        console.log('是否配送', e)
        this.delivery = e.detail.value
      },
      pay () {
        let that = this
        // 判断是否选择了地址
        if (this.delivery && !this.order.address) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
        if (this.isLoading) return
        this.isLoading = true
        utils.wxLoading()
        const userInfo = uni.getStorageSync('userInfo')
        console.log(this.order)
        let item = utils.deepClone(this.order)
        User.prePayment({
          data: {
            form: {
              "device_info": "1",
              "body": "商品描述",
              "detail": "商品详情",
              "out_trade_no": item.orderNumber,
              "total_fee": +item.total,
              "spbill_create_ip": "0.0.0.0",
              "time_start": Date.now(),
              "notify_url": "http://www.weixin.qq.com/wxpay/pay.php",
              "product_id": utils.randomWord(false, 16),
              "openid": userInfo.openid
            }
          }
        }).then(res => {
          console.log('请求支付接口')
          console.log(res)
          let result = res.data.body
          uni.requestPayment({
            nonceStr: result.nonceStr,
            timeStamp: result.timeStamp,
            package: result.packageInfo,
            paySign: result.sign,
            signType: 'MD5',
            success (payRes) {
              console.log('支付完成')
              console.log(payRes)
              Order.updateOrder({ data: {
                form: {
                  updateTime: utils.formatTime(new Date()),
                  orderNumber: item.orderNumber,
                  status: 2
                },
                query: {},
                pagination: {}
              }}).then(res => {
                uni.showToast({
                  title: '支付完成',
                  icon: 'success'
                });
                console.log('更新支付状态', res)
                that.getOrderDetail()
              }).catch(err => console.log(err))
            },
            fail: (err) => {
              console.log('支付失败');
              console.error(err)
              this.isLoading = false
              uni.hideLoading()
              utils.wxToastFail('放弃支付')
            },
            complete () {
              uni.hideLoading()
            }
          })
        }).catch(err => {
          utils.wxToastFail('支付失败')
        }).finally(() => {
          this.isLoading = false
        })
      }
    },
    mounted (options) {
      this.options = this.$scope.options
      this.getOrderDetail()
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #EFEFEF;
  }
  .cell {
    box-sizing: border-box;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 1rpx;
    background-color: #FFF;
    .label {
      color: #333333;
      font-size: 28rpx;
      .location-detail {
        font-weight: bold;
        max-width: 70%;
      }
    }
    .value {
      flex: 1;
      font-size: 28rpx;
    }
    .time {
      color: #0CB9F2;
      text-align: right;
    }
  }
  .item {
    box-sizing: border-box;
    margin-top: 20rpx;
    padding: 0 20rpx;
    background-color: #FFF;

    .title {
      color: #333333;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: #EFEFEF 1rpx solid;
      padding: 20rpx 0;

      .name {
        display: flex;
        align-items: center;

        image {
          width: 44rpx;
          height: 44rpx;
          margin-right: 20rpx;
          background-color: #D8D8DD;
          border-radius: 50%;
        }
      }

      .status {
        font-weight: normal;
        color: #FF4A4A;
      }
    }

    .main {
      box-sizing: border-box;
      padding: 20rpx 0;
      display: flex;

      image {
        flex-shrink: 0;
        width: 140rpx;
        height: 140rpx;
        border-radius: 10rpx;
        background-color: #D8D8D8;
      }

      .info {
        flex: 1;
        box-sizing: border-box;
        padding-left: 20rpx;

        .name {
          color: #333333;
          font-size: 24rpx;
          height: 100rpx;
          line-height: 1.5;
        }

        .price {
          color: #FF4A4A;
          font-size: 24rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: bold;

          text {
            color: #666;
          }
        }
      }
    }

    .btn-group {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 20rpx 0;
      border-top: #EFEFEF 1rpx solid;
      flex-direction: row-reverse;

      .total {
        color: #333333;
        font-size: 24rpx;
        line-height: 40rpx;
        flex-justify-self: flex-end;
        margin-right: auto;

        .total-price {
          text {
            color: #FF4A4A;
          }
        }

        .count {
          color: #666;
        }
      }

      button {
        width: 120rpx;
        height: 58rpx;
        border: #FF4A4A 2rpx solid;
        border-radius: 29rpx;
        margin: 10rpx;
        color: #FF4A4A;
        font-size: 28rpx;
        line-height: 58rpx;
        background-color: #FFF;
      }
    }
  }
  .amount-info {
    font-size: 28rpx;
    color: #333333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text {
      font-weight: bold;
      padding-right: 20rpx;
    }
  }
  .order-info {
    color: #333333;
    font-size: 28rpx;
  }
  .mt {
    margin-top: 20rpx;
  }
  .message {
    color: #999999;
    font-size: 18px;
    line-height: 36px;
    text-align: center;
    padding-top: 100px;
  }
</style>
